package com.lg.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.wxpay.sdk.WXPayUtil;
import com.system.base.ApiResult;
import com.system.base.pay.AbstractPayTemplate;
import com.system.config.PayTemplateContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 支付测试
 * 
 * @author kaifa002
 *
 */
@SuppressWarnings("rawtypes")
@RestController
@Slf4j
public class PayController {

	@Resource
	private PayTemplateContext payTemplateContext;

	/**
	 * 测试使用 ali、wx、wx2进行分别传参，查看日志打印结果
	 * 
	 * @param payType
	 * @return
	 */
	@RequestMapping("payTest")
	public ApiResult payTest(String payType) {

		log.info("该付款类型：{}", payType);
		AbstractPayTemplate payTemplate = payTemplateContext.getTemplateInstance(payType);

		Map<String, String> requestMap = new HashMap<>();
		requestMap.put("no", numsToRandom());
		ApiResult apiResult = payTemplate.run(requestMap);

		return apiResult;
	}

	/**
	 * ali、wx回调函数
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/notifyUrl")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String resXml = "";
		try {
			log.info("notifyUrl支付回调方法，开始进入。。。");
			// 读取参数
			StringBuffer sb = new StringBuffer();
			InputStream inputStream = request.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String str = null;
			while ((str = in.readLine()) != null) {
				sb.append(str);
			}
			in.close();
			inputStream.close();
			// 解析xml成map
			sb.append("<?xml version='1.0' encoding='UTF-8'?><root><out_trade_no>LG202211290025541741454221</out_trade_no></root>");
			Map<String, String> params = WXPayUtil.xmlToMap(sb.toString());
			log.info("支付返回回来的参数：" + params);
			// 多个来源判断
			String traceNo = params.get("trace_no");
			if (StringUtils.isEmpty(traceNo)) {
				traceNo = params.get("out_trade_no");
			}
			// 通过traceNo查询该订单是否已经处理，查询该订单来源
			String payType = "nbcb"; // wx,alipay
			AbstractPayTemplate payTemplate = payTemplateContext.getTemplateInstance(payType);
			resXml = payTemplate.notifyUrl(params);
			log.info("支付回调结果：" + resXml);
		} catch (Exception e) {
			e.printStackTrace();
		}
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
	}

	/**
	 * 将生成的时间+num位随机数，打乱
	 * 
	 * @return
	 */
	public static String numsToRandom() {
		String randomNO = randomNO(4);
//		char[] chars = randomNO.toCharArray();
//		List<String> list = new ArrayList<>();
//		for (char aChar : chars) {
//			list.add(aChar + "");
//		}
//		Collections.shuffle(list);
//
//		StringBuffer sb = new StringBuffer();
//		list.forEach(ch -> sb.append(ch));
//		return sb.toString();
		return randomNO;
	}

	/**
	 * 唯一编号 = 点前时间年月日时分秒+num位随机数
	 * 
	 * @return
	 */
	public static String randomNO(int num) {
		String newsNo = timeNoYMDHMS();
		long random = getRandom(num);
		return newsNo + random;
	}

	/**
	 * 获取当前时间 yyyyMMddHHmmss
	 * 
	 * @return
	 */
	public static String timeNoYMDHMS() {
		// 设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmsss");
		// new Date()为获取当前系统时间，也可使用当前时间戳
		String newsNo = df.format(new Date());
		return newsNo;
	}

	/**
	 * 生成固定长度随机码
	 * 
	 * @param n 长度
	 */
	public static long getRandom(long n) {
		long min = 1, max = 9;
		for (int i = 1; i < n; i++) {
			min *= 10;
			max *= 10;
		}
		long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min;
		return rangeLong;
	}

}
